import json
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

discount_reward_type_list_api = Blueprint('discount_reward_type_list_api', __name__)
discount_store_proj_api = Blueprint('discount_store_proj_api', __name__)
discount_store_schedule_api = Blueprint('discount_store_schedule_api', __name__)
discount_store_json_api = Blueprint('discount_store_json_api', __name__)


# 获取数据列表
def get_proj_list(params, result_data):
  data = DiscountStoreProj.query.order_by("id").all()
  result = []

  for que in data:
    id = int(que.id)
    remark = que.remark
    goods = json.loads(que.goods)
    tmp = {'id': id, 'remark': remark, 'goods': goods}
    result.append(tmp)
  return result


def uploadList(params, result_data):
  deleteList = params['delete']
  for deleteItem in deleteList:
    _id = deleteItem['id']
    if _id != -1:
      itemData = DiscountStoreProj.query.filter_by(id=_id).first()
      db.session.delete(itemData)
      db.session.commit()

  for item in params['list']:
    if item['id'] == -1:
      newItem = DiscountStoreProj(
        remark=item['remark'],
        goods=json.dumps(item['goods']),
      )
      db.session.add(newItem)
    else:
      DiscountStoreProj.query.filter_by(id=item['id']).update({
        "remark": item['remark'],
        "goods": json.dumps(item['goods']),
      })
  db.session.commit()
  result_data['data']['msg']='更新成功'
  return result_data

def proj_id_list(param,result_data):
  data = DiscountStoreProj.query.order_by("id").all()
  result = []

  for que in data:
    id = int(que.id)
    remark = que.remark
    # goods = json.loads(que.goods)
    # tmp = {'id': id, 'remark': remark, 'goods': goods}
    tmp = {'id': id, 'remark': remark}
    result.append(tmp)
  return result


@discount_reward_type_list_api.route('/discount_reward_type_list', methods=['GET', 'POST'])
def discount_reward_type_list():
    with open(STATIC_PATH + 'reward_type_list.json', encoding='utf8') as f:
        data = json.load(f)
    return jsonify({"data": data})


@discount_store_proj_api.route("/discount_store_proj", methods=['GET', 'POST'])
def discount_store_proj():
  params = json.loads(request.data)
  _action = params['action']
  result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
  # 策略模式、调用具体action方法
  result = notify_result(_action)(params, result_data)
  if result == -1:
    return {'result': [], info: 'action错误'}
  # response = make_response(jsonify({'result': result}))
  # response.headers['Access-Control-Allow-Origin'] = 'http://54.223.156.94'
  return jsonify({'result': result})

# 策略模式调用功能
def notify_result(func):
  mesthods = {
    'get_proj_list': get_proj_list,
    'update': uploadList,
    "proj_id_list": proj_id_list
  }

  return mesthods.get(func, -1)


def getSchedule(params, result_data):
  data = DiscountStoreSchedule.query.order_by("id").all()
  result = []

  for que in data:
    id = int(que.id)
    begin_time = que.begin_time
    end_time = que.end_time
    pid = que.pid
    sid_list = que.sid_list
    # goods = json.loads(que.goods)
    # tmp = {'id': id, 'remark': remark, 'goods': goods}
    tmp = {'id': id, 'end_time': end_time, 'begin_time': begin_time, 'pid': pid, 'sid_list': sid_list}
    result.append(tmp)
  return result


def update_schedule(params, result_data):
  deleteList = params['delete']
  for deleteItem in deleteList:
    _id = deleteItem['id']
    if _id != -1:
      itemData = DiscountStoreSchedule.query.filter_by(id=_id).first()
      db.session.delete(itemData)
      db.session.commit()

  for item in params['list']:
    if item['id'] == -1:
      newItem = DiscountStoreSchedule(
        begin_time=item['begin_time'],
        end_time=item['end_time'],
        pid=item['pid'],
        sid_list=item['sid_list']
      )
      db.session.add(newItem)
    else:
      DiscountStoreSchedule.query.filter_by(id=item['id']).update({
        "begin_time":item['begin_time'],
        "end_time":item['end_time'],
        "pid":item['pid'],
        "sid_list":item['sid_list']
      })
    db.session.commit()
  result_data['data']['msg'] = '更新成功'
  return result_data

def politic(func):
  mesthods= {
    "get_list": getSchedule,
    "update_schedule": update_schedule
  }

  return mesthods.get(func, -1)

@discount_store_schedule_api.route('/discount_store_schedule', methods=['GET', 'POST'])
def discount_store_schedule():
  params = json.loads(request.data)
  _action = params['action']
  result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
  # 策略模式、调用具体action方法
  result = politic(_action)(params, result_data)
  if result == -1:
    return {'result': [], info: 'action错误'}
  return jsonify({'result': result})


@discount_store_json_api.route('/discount_store_json/<int:is_push>', methods=['GET', 'POST'])
def discount_store_json(is_push):
  # 转化文件
  result_data = {}
  proj_data = DiscountStoreProj.query.all()
  schedule_data = DiscountStoreSchedule.query.all()
  proj = {}
  schedule = []
  for item in proj_data:
    # item.id = str(item.id)
    new_item = {'goods':[]}
    goods = json.loads(item.goods)
    for good in goods:
      a = []
      a.append(good['a']['type'])
      a.append(good['a']['id'])
      a.append(good['a']['num'])
      limit_num = good['limit_num']
      raw_price = good['raw_price']
      sale_price = good['sale_price']
      new_item['goods'].append({"a":a, "limit_num":limit_num, "raw_price":raw_price, "sale_price":sale_price})
    proj[str(item.id)] = new_item

  for item in schedule_data:
    schedule.append(
        {
          "begin_time": fomat_date_str(item.begin_time),
          "end_time":fomat_date_str(item.end_time),
          "pid": item.pid,
          "sid": ToSidList(item.sid_list)
        }
    )

  result_data['proj'] = proj
  result_data['schedule'] = schedule

  response = DownLoad('onsale', result_data, is_push)

  return response

